package com.myhome.demo;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Event;
import com.dianping.cat.message.Transaction;
import com.dianping.cat.message.spi.MessageTree;

import java.util.Random;

/**
 * Created by Rod on 2018/1/23.
 */
public class CatDemo {
    private static final String JDBC_CONNECTION = "";

    public void CatTest() {
        String pageName = "sql.method";
        String serverIp = "";
        double amount = 0;
        Transaction t = Cat.newTransaction("SQL", pageName);
        try {
            System.out.println("debug...");
            Cat.getProducer().logEvent("your event type", "your event name", Event.SUCCESS, "keyValuePairs");
            Cat.logMetricForSum("记录一个业务指标",8.9);
            t.setStatus(Transaction.SUCCESS);
        } catch (Exception e) {
            Cat.getProducer().logError(e);//用log4j记录系统异常，以便在Logview中看到此信息
            t.setStatus(e);
        } finally {
            t.complete();
        }
    }
    private void sendSQLMsg(String name, String domain, String method, String serverIp) throws InterruptedException {
        Transaction t = Cat.newTransaction("SQL", "sql.method");
        Cat.logEvent("SQL.Method", method);
        Cat.logEvent("SQL.Database", String.format(JDBC_CONNECTION, serverIp, name));
        MessageTree tree = Cat.getManager().getThreadLocalMessageTree();
        tree.setDomain(domain);
        Thread.sleep(500 + new Random().nextInt(1000));
        int nextInt = new Random().nextInt(3);
        if (nextInt % 2 == 0) {
            t.setStatus(Transaction.SUCCESS);
        } else {
            t.setStatus(String.valueOf(nextInt));
        }
        t.complete();
    }

    public static void main(String[] args) {
        CatDemo demo = new CatDemo();
        //demo.CatTest();
        try {
            demo.sendSQLMsg("","","","");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
